package com.softeware.control;

import jakarta.servlet.*;
import jakarta.servlet.http.*;
import jakarta.servlet.annotation.*;

import java.io.IOException;
import java.util.Hashtable;

@WebServlet("/registerServlet")
public class registerServlet extends HttpServlet {
    private ServletContext application;
    Hashtable<String, String> users;
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request,response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        application = getServletContext();

        String username = request.getParameter("username");
        String password = request.getParameter("password");

        buildMap();

        users = (Hashtable<String, String>) application.getAttribute("users");

        if(users.containsKey(username)){
            request.getRequestDispatcher("Login.jsp?info=unRegister&key="+users.get(username)).forward(request,response);
        }

        users.put(username,password);
        application.setAttribute("users",users);
        request.getSession().setAttribute("username",username);
        request.getRequestDispatcher("main.jsp").forward(request,response);
    }
    private void buildMap() {
        users = (Hashtable<String, String>) application.getAttribute("users");
        if (users == null) {
            users = new Hashtable<>();
            application.setAttribute("users", users);
        }
    }

}